using Digitalmes.Domain.Entities.Mes.Masters;
using Digitalmes.Domain.Entities.Mes.Processes;

namespace Digitalmes.Application.Services.Impl;

internal sealed class WorkstationQueryService(IRepository<MdWorkstation> repo, IRepository<ProcOperation> operatioRepo) : IWorkstationQueryService
{
    public async Task<MdWorkstation?> GetWorkstationAsync(string lineCode, string workstationCode)
    {
        return await repo.AsQueryable()
            .Includes(m => m.Line)
            .Where(m => m.Line!.LineCode == lineCode)
            .FirstAsync(m => m.WsCode == workstationCode);
    }

    public async Task<(ProcOperation?, MdWorkstation?)> GetOperationAsync(string lineCode, string workstationCode)
    {
        var workstation = await GetWorkstationAsync(lineCode, workstationCode);
        if (workstation == null)
        {
            return (default, default);
        }
        
        var operation = await operatioRepo.FirstOrDefaultAsync(m => m.LineId == workstation.LineId && SqlSugar.SqlFunc.JsonArrayAny(m.WsIds, workstation.Id));
        return (operation, workstation);
    }
}
